package com.unitd.base.frame.handler;

import com.unitd.base.frame.exception.LogisticsException;
import com.unitd.base.frame.spring.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常信息处理器类,用于处理整个app遇到异常时的通用异常处理器
 * @filename GlobalExceptionHandler.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2018-01-30
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 全局异常捕捉处理
	 * @param e 异常
	 * @return 异常的json对象
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public AjaxResult exceptionHandler(Exception e) {
		log.error("捕获到Exception异常", e);

		AjaxResult resp = new AjaxResult();
		if (e instanceof LogisticsException) {
			LogisticsException e1 = (LogisticsException) e;
			resp.setCode(e1.getCode());
			resp.setMsg(e1.getMessage());
		} else if (e instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
			resp.setCode(HttpStatus.METHOD_NOT_ALLOWED.value());
			resp.setMsg(e.getMessage());
		} else if (e instanceof org.springframework.web.HttpMediaTypeException) {
			resp.setCode(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value());
			resp.setMsg(e.getMessage());
		} else if (e instanceof RuntimeException) {
			resp.setCode(500);
			resp.setMsg(e.getMessage());
		} else {
			resp.setCode(500);
			resp.setMsg("系统繁忙");
			log.error("", e);
		}
		return resp;
	}
	/**
	 * 自定义异常捕捉处理
	 * @param e 异常
	 * @return 异常的json对象
	 */
	@ExceptionHandler(LogisticsException.class)
	@ResponseBody
	public AjaxResult exceptionHandler(LogisticsException e) {
		log.error("捕获到LogisticsException异常", e);

		AjaxResult resp = new AjaxResult();
		resp.setCode(500);
		resp.setMsg(e.getMessage());
		return resp;
	}
}